<template>
  <!-- 班级信息页面 -->
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <treeIndex :deptOptions="deptOptions" @handleNode="handleNodeClick" :title="'学院信息'"></treeIndex>
      </el-col>
      <el-col :span="20" :xs="24">
        <searchForm :formOptions="formOptions" @onSearch="onSearch" @onReset="onReset" :formLabelWidth="formLabelWidth"
          v-show="showSearch" />
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['basic:class:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['basic:class:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['basic:class:remove']">删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table :data="roleList" @selection-change="handleSelectionChange" v-loading="loading">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="所属院系" prop="deptNames" align="center" width="190" :show-overflow-tooltip="true" />
          <el-table-column label="专业名称" prop="specialtyName" :show-overflow-tooltip="true" align="center" width="180" />
          <el-table-column label="入学年级" prop="gradeName" align="center" width="80" />
          <el-table-column label="班号" prop="classCode" :show-overflow-tooltip="true" align="center" width="100" />
          <el-table-column label="班级名称" :show-overflow-tooltip="true" prop="name" align="center" width="160" />
          <el-table-column label="班级人数" prop="classSize" align="center" />
          <el-table-column label="学制" prop="specialtyEs" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.bc_speciality_type" :value="scope.row.specialtyEs"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="类型" prop="specialtyType" align="center" />
          <!-- <el-table-column label="班级性质" prop="classNature" align="center" /> -->
          <!-- <el-table-column label="辅导员" prop="roleSort" align="center" />
      <el-table-column label="班主任" prop="roleSort" align="center" />
      <el-table-column label="班长" prop="monitor" align="center" /> -->
          <el-table-column label="创建时间" prop="createTime" :show-overflow-tooltip="true" align="center" />
          <!-- <el-table-column label="创建人" prop="createBy" align="center" /> -->
          <el-table-column label="操作" align="center" fixed="right" width="110">

            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
                v-hasPermi="['basic:class:edit']">修改</el-button>
              <el-button size="mini" type="text" @click="handleDelete(scope.row)"
                v-hasPermi="['basic:class:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>


    <!-- 添加或修改班级信息 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" ppend-to-body @close="CloseIn" destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属院系" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择" clearable class="elSelect" @change="handleChange"  style="width: 100%">
                <el-option v-for="item in collegeSelectList" :key="item.deptId" :label="item.deptName"
                  :value="item.deptId"></el-option>
              </el-select>
              <!-- <el-cascader ref="cascaderAddr" v-model="form.deptId" :options="deptOptions" 
                :props="{ value: 'id', currentLabels: 'label', checkStrictly: true }" @change="handleChange"></el-cascader> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="specialtyId">
              <el-select v-model="form.specialtyId" placeholder="请选择所专业" clearable style="width: 100%">
                <el-option v-for="dict in professionList" :key="dict.VALUE" :label="dict.TITILE" :value="dict.VALUE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入学年级" prop="gradeId">
              <el-select v-model="form.gradeId" placeholder="请选择入学年级" clearable style="width: 100%">
                <el-option v-for="dict in gradeList" :key="dict.VALUE" :label="dict.TITILE" :value="dict.VALUE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班号" prop="classCode">
              <el-input v-model.trim="form.classCode" placeholder="请输入班号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级名称" prop="name">
              <el-input v-model.trim="form.name" placeholder="请输入班级名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="班级人数" prop="classNumber">
              <el-input v-model.trim="form.classNumber" type="number" placeholder="请输入班级人数" maxlength="3" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="班级性质" prop="classNature">
              <el-input v-model.trim="form.classNature" placeholder="请输入班级性质"  maxlength="30"/>
            </el-form-item>
          </el-col>-->
          <!-- <el-col :span="12">
            <el-form-item label="辅导员" prop="instructor">
              <el-input v-model.trim="form.instructor" placeholder="请输入辅导员" maxlength="10" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班主任" prop>
              <el-input v-model.trim="form.roleName" placeholder="请输入班主任" maxlength="10" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班长" prop="monitor">
              <el-input v-model.trim="form.monitor" placeholder="请输入班长" maxlength="10" />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { deptTreeSelect } from "@/api/system/user";
import { getGradeSelect } from "@/api/information/gradeInfor";
import { getSpecialityByDeptId } from "@/api/information/unitMajor";
import Validators from "@/utils/validate.js";
import {
  collegeSelect
} from "@/api/information/studentInfor"
import {
  classList,
  addClass,
  updataClass,
  delClass,
  classInfor, getSpecialityTree
} from "@/api/information/classInfor";
import { getDicts } from "@/api/system/dict/type";
import searchForm from "@/components/Search/searchForm.vue";
import treeIndex from "@/components/tree/index.vue";

export default {
  name: "Role",
  dicts: ["sys_normal_disable", 'bc_speciality_type'],
  components: { searchForm, treeIndex },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 部门数据
      professionList: [],
      // 入学年级数据
      gradeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      formLabelWidth: "90px",
      formOptions: [
        {
          label: "专业名称",
          prop: "specialtyName",
          element: "el-input",
          placeholder: "请输入专业名称"
        },
        {
          label: "入学年级",
          prop: "gradeId",
          element: "el-select",
          options: []
        },
        {
          label: "班号",
          prop: "classCode",
          element: "el-input",
          placeholder: "请输入班号"
        },
        {
          label: "班级名称",
          prop: "name",
          element: "el-input",
          placeholder: "请输入班级名称"
        },
        {
          label: "学制",
          prop: "specialtyEs",
          element: "el-select",
          options: [],
          placeholder: "请选择学制"
        },
        {
          label: "类型",
          prop: "specialtyType",
          element: "el-select",
          options: [
          ],
          placeholder: "请选择类型"
        },
      ],
      deptOptions: [],
      collegeSelectList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {
        deptId: "",
        classNumber: "",
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "请选择所属院系", trigger: "change" }
        ],
        specialtyId: [
          { required: true, message: "请选择专业", trigger: "change" }
        ],
        gradeId: [
          { required: true, message: "请选择入学年级", trigger: "change" }
        ],
        classCode: [
          {
            required: true,
            text: "请输入班号",
            validator: Validators.isStr,
            trigger: "blur"
          }
        ],
        name: [
          {
            required: true,
            text: "请输入班级名称",
            validator: Validators.isStr,
            trigger: "blur"
          }
        ],
        classNumber: [
          { required: false, message: "请输入班级人数", trigger: "blur" },
          { message: "只能输入数字", pattern: /^[0-9]+$/, trigger: "blur" }
        ],
        // classNature: [
        //   {
        //     required: true,
        //     text: "请输入班级性质",
        //     validator: Validators.isStr,
        //     trigger: "blur"
        //   }
        // ],

        instructor: [{ required: false, trigger: "blur" }],
        teacherName: [{ required: false, trigger: "blur" }],
        monitor: [{ required: false, trigger: "blur" }]
      }
    };
  },
  created() {
    this.getDeptTree();
    // this.getList();
    this.getGrade();
    getDicts("basic_speciality_type").then(res => {
      this.formOptions[5].options = res.data.map(item => {
        return {
          value: item["dictValue"],
          label: item["dictLabel"]
        };
      });
    });
    getDicts("bc_speciality_type").then(res => {
      this.formOptions[4].options = res.data.map(item => {
        return {
          value: item["dictValue"],
          label: item["dictLabel"]
        };
      });
    });
  },
  methods: {
    // 获取搜索表单提交的数据
    onSearch(val) {
      // 查询条件和分页数据合并
      this.queryParams = Object.assign(this.queryParams, val);
      // console.log(arr);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    onReset(data) {
      console.log(data);
      this.queryParams.deptId = ''
      this.queryParams = Object.assign(this.queryParams, data);
      this.getList();

    },
    // tree树形选中的值
    handleNodeClick(data) {
      this.deptId = data.id;
      this.deptNameTree = data.label;
      this.queryParams.deptId = data.id;
      this.getList();
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      getSpecialityTree().then(response => {
        console.log(response);
        this.deptOptions = response.data;
        // this.queryParams.deptId = response.data[0].id;
        this.getList();
      });
    },
    handleChange(value) {
      // if (value) {
      //   this.form.deptId = value[value.length - 1];
      //   this.getSpeciality();
      // }
      this.getSpeciality();
      // this.form.deptId = value[2];
      // debugger
      // getSpecialityByDeptId({ deptId: this.form.deptId }).then(res => {
      //   this.professionList = res.data;
      // });
    },
    getSpeciality() {
      getSpecialityByDeptId({ deptId: this.form.deptId }).then(res => {
        this.professionList = res.data;
      });
    },
    // 清除表单
    CloseIn() {
      this.form = {};
      this.open = false;
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      classList(this.queryParams).then(response => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取部门信息
    department() {
      collegeSelect().then(res => {
        this.collegeSelectList = res.data;
        console.log(this.deptOptions, " this.deptOptions");
        // this.queryParams.deptId = res.data[0].id
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.name = selection.map(item => item.name);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.department();
      this.open = true;
      this.title = "添加班级信息";
    },
    // 获取年级信息
    getGrade() {
      getGradeSelect().then(res => {
        console.log(res);
        this.gradeList = res.data;
        this.formOptions[1].options = res.data.map(item => {
          return {
            value: item["VALUE"],
            label: item["TITILE"]
          };
        });
      });
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.department();
      const roleId = row.id || this.ids;
      await classInfor(roleId).then(response => {
        this.form = response.data;

        this.getSpeciality();
        this.open = true;
        this.title = "修改班级信息";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            // if(this.form.classNumber == '') {

            // }
            this.form.classNumber = Number(this.form.classNumber)
            updataClass(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.form = {};
              this.getList();
            });
          } else {
            addClass(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.form = {};
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id || this.ids;
      this.name = row.name || this.name;
      this.$modal
        .confirm('是否确认删除班级名称"' + this.name + '"的数据项？')
        .then(function () {
          return delClass(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    }
  }
};
</script>